const watermarks = {};

function creatWatermark(el, binding) {
    const { width, height } = el.getBoundingClientRect();
    const watermarkKey = el.getAttribute('data-watermark-key');
    let canvas = el.querySelector(`.v-watermark${watermarkKey}`);
    if (!canvas) {
        canvas = document.createElement('canvas');
        canvas.className = `v-watermark${watermarkKey}`;
        canvas.style.position = 'absolute';
        canvas.style.zIndex = 1995;
        canvas.style.top = 0;
        canvas.style.left = 0;
        canvas.style.pointerEvents = 'none';
        el.appendChild(canvas);
    }

    canvas.width = width;
    canvas.height = height;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.translate(width * 0.5, height * 0.5);
    ctx.rotate(-20 * Math.PI / 180);
    ctx.translate(-width * 0.5, -height * 0.6);
    ctx.font = '16px YaHei';
    // ctx.fillStyle = 'red';
    ctx.fillStyle = 'rgba(180, 180, 180, .18)';
    ctx.textBaseline = 'hanging';
    const textWidth = ctx.measureText(binding.value).width;
    const countY = Math.ceil(width / 300);
    const countX = Math.ceil(height * 1.5 / textWidth);
    Array(countY).fill().forEach((_, i) => {
        Array(countX).fill().forEach((__, j) => {
            ctx.fillText(binding.value || '', (width / countY + 50) * i, (height / countX + 50) * j);
        });
    });
}

const unmounted = (el) => {
    const watermarkKey = el.getAttribute('data-watermark-key');
    if (!watermarkKey) return;
    watermarks[watermarkKey].resizeObserver.disconnect();
    watermarks[watermarkKey].resizeObserver = null;
};

const updateWatermark = (el, binding) => {
    const watermarkKey = el.getAttribute('data-watermark-key');
    if (!watermarkKey) return;
    clearTimeout(watermarks[watermarkKey].timer);
    watermarks[watermarkKey].timer = setTimeout(() => {
        creatWatermark(el, binding);
    }, 100);
};

const mounted = (el, binding) => {
    let watermarkKey = el.getAttribute('data-watermark-key');
    if (!watermarkKey) {
        watermarkKey = Math.random().toString().slice(2);
        el.setAttribute('data-watermark-key', watermarkKey);
    }
    watermarks[watermarkKey] = {
        timer: null,
        resizeObserver: new ResizeObserver(() => { updateWatermark(el, binding); }),
    };
    // 开始观察目标元素
    watermarks[watermarkKey].resizeObserver.observe(el);
};

export default {
    mounted,
    updated(el, binding) {
        updateWatermark(el, binding);
    },
    unmounted,
};
